if (!sptlght)
    var sptlght = {};
/**
 * @namespace - the parent class of all data models for Protovis-based Visualization Tool Data
 */
if (!sptlght.models)
    sptlght.models = {};
/**
 * @namespace - the parent class for utility classes focused on visualization tools.
 */
if (!sptlght.utils)
    sptlght.utils = {};

sptlght.utils.SpotlightUtils = {};

sptlght.utils.SpotlightUtils.getSystemSpotlightData = function (callback) {
    var spurl = "/addama-rest/primary-repo/path/spotlight/system/search?FREE_TEXT=*&PROJECTION=desc&PROJECTION=alias";
    Ext.Ajax.request({
        url: spurl,
        method: "GET",
        success: function(response) {
            var searchResultObj = Ext.util.JSON.decode(response.responseText);
            eventManager.fireStatusMessageEvent({ text: "System spotlights results Count:" + searchResultObj.numberOfResults, level: "info" });
            sptlght.utils.SpotlightUtils.loadSystemResultArray(searchResultObj, function() {
                callback();
            });
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + spurl, level: "error" });
            callback();
        }
    });
    //callback();
};

sptlght.utils.SpotlightUtils.postSystemSpotlightData = function (key, postSpotlightJson, callback) {
    /*"http://ravioli:8080/addama-rest/primary-repo/path/users/jlin/YO 29/create
     ?JSON={'uri':'/addama-rest/dudley-sample/path/datasource/YO/YO 29','type':'sample','desc':'Sake-Genotype'}"*/
    var spurl = "/addama-rest/primary-repo/path/users/" + sptlght.utils.userspotlight + "/" + key + "/create";
    postDudleyAnnotations(spurl, postSpotlightJson, callback);
};

if (!sptlght.utils.userspotlight)
    sptlght.utils.userspotlight = null;

sptlght.utils.SpotlightUtils.getPersonalSpotlightData = function (email, callback) {
    sptlght.utils.userspotlight = email.split("@")[0];
    var spurl = "/addama-rest/primary-repo/path/spotlight/personal/" + sptlght.utils.userspotlight + "/search?FREE_TEXT=*&PROJECTION=desc&PROJECTION=alias";
    Ext.Ajax.request({
        url: spurl,
        method: "GET",
        success: function(response) {
            var searchResultObj = Ext.util.JSON.decode(response.responseText);
            eventManager.fireStatusMessageEvent({ text: "Personal spotlights results Count:" + searchResultObj.numberOfResults, level: "info" });
            sptlght.utils.SpotlightUtils.loadPersonalResultArray(searchResultObj, function() {
                callback();
            });
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({ text: "Personal Results failed for url:" + spurl, level: "error" });
            callback();
        }
    });
    callback();
};


sptlght.utils.SpotlightUtils.postSpotlightData = function (type, key, postSpotlightJson, callback) {
    /*"http://ravioli:8080/addama-rest/primary-repo/path/users/jlin/YO 29/create
     ?JSON={'uri':'/addama-rest/dudley-sample/path/datasource/YO/YO 29','type':'sample','desc':'Sake-Genotype'}"*/
    var spurl = "/addama-rest/primary-repo/path/spotlight/personal/" + sptlght.utils.userspotlight + "/" + key;
    if (type == 'System') {
        spurl = "/addama-rest/primary-repo/path/spotlight/system/" + key;
    }
    Ext.Ajax.request({
        url: spurl + "/meta",
        method: "GET",
        success: function() {
            Ext.getCmp("LIMSSpotlightId").close();
            Ext.MessageBox.alert(key + " already exists in spotlights.");
            return true;
        },
        failure: function(response) {
            var status = response.status;
            if (status == '404') {
                postDudleyAnnotations(spurl + "/create", postSpotlightJson, callback);
            }
        }
    });
};

sptlght.utils.SpotlightUtils.deleteSpotlightData = function (type, key, callback) {
    var spurl = "/addama-rest/primary-repo/path/spotlight/personal/" + sptlght.utils.userspotlight + "/" + key + "/delete";
    if (type == 'System') {
        spurl = "/addama-rest/primary-repo/path/spotlight/system/" + key + "/delete";
    }
    postDudleyAnnotations(spurl, {}, callback);
};

sptlght.utils.SpotlightUtils.dblclick = function (key) {
    mainPanel.activate(samplesPanel);
    key = key.replace(/ /, "");
    if (key.indexOf("YO") != -1) {
        Dudley.lims.YOStrain.loadStrain(key);
    } else if (key.indexOf("YAD") != -1) {
        Dudley.lims.YADStrain.setYADLoaded(true);
        Dudley.lims.YADStrain.loadStrain(key);
    } else if (key.indexOf("YCR") != -1) {
        Dudley.lims.Crossing.setCrosssingLoaded(false);
        Dudley.lims.Crossing.setCrossingSearchParams(key, "All");
        Dudley.lims.Crossing.loadCrossingSearch();
    } else if (key.indexOf("DO") != -1) {
        Dudley.lims.DeletionOligo.setDOLoaded(false);
        Dudley.lims.DeletionOligo.setSearchParams(key, "All");
        Dudley.lims.DeletionOligo.loadSearchResult();
    } else if (key.indexOf("YPG") != -1) {
        Dudley.lims.YPGStrain.setYPGLoaded(false);
        Dudley.lims.YPGStrain.loadYPG(key);
    } else if (key.indexOf("YSEQ") != -1) {
        if (!Dudley.lims.sequencingmgr.getSeqLoaded()) {
            Dudley.lims.sequencingmgr.loadSequencingManagement(function() {
                Dudley.lims.sequencingmgr.setSeqLoaded(true);
                Dudley.lims.YSEQEntry.setEntryLoaded(true);
                Dudley.lims.YSEQEntry.setSearchParams(key, "seqName");
                Dudley.lims.YSEQEntry.loadGoSearch();
                mainPanel.activate(sequencingPanel);
            });
        } else {
            mainPanel.activate(sequencingPanel);
            Dudley.lims.YSEQEntry.setEntryLoaded(false);
            Dudley.lims.YSEQEntry.setSearchParams(key, "seqName");
            Dudley.lims.YSEQEntry.loadGoSearch();
        }
    } else if (key.indexOf("YCGS") != -1) {
        if (!Dudley.lims.sequencingmgr.getSeqLoaded()) {
            Dudley.lims.sequencingmgr.loadSequencingManagement(function() {
                Dudley.lims.sequencingmgr.setSeqLoaded(true);
                Dudley.lims.YSEQCGS.setCGSLoaded(false);
                Dudley.lims.YSEQCGS.setCGSSearchParams(key, "All");
                Dudley.lims.YSEQCGS.loadCGSSearch();
                mainPanel.activate(sequencingPanel);                
            });
        } else {
            mainPanel.activate(sequencingPanel);
            Dudley.lims.YSEQCGS.setCGSLoaded(false);
            Dudley.lims.YSEQCGS.setCGSSearchParams(key, "All");
            Dudley.lims.YSEQCGS.loadCGSSearch();
        }
    }
};

sptlght.utils.SpotlightUtils.getSpotlightGrid = function (gridType, gridstore) {
    var handlerFunction = function() {
        var mySpGrid = Ext.getCmp(gridType + "SpotlightGridId");
        var recSelected = mySpGrid.getSelectionModel().getSelected();
        sptlght.utils.SpotlightUtils.deleteSpotlightData("Personal", recSelected.data.name, function() {
            mySpGrid.store.remove(recSelected);
        });
    };

    if (gridType == 'System') {
        handlerFunction = function() {
            var mySpGrid = Ext.getCmp(gridType + "SpotlightGridId");
            var recSelected = mySpGrid.getSelectionModel().getSelected();
            Ext.MessageBox.confirm('Message', 'Please confirm removal of ' + recSelected.data.name + ' as a system spotlight.', function(btn) {
                if (btn == 'yes') {
                    sptlght.utils.SpotlightUtils.deleteSpotlightData("System", recSelected.data.name, function() {
                        mySpGrid.store.remove(recSelected);
                    });
                } else {
                    eventManager.fireStatusMessageEvent({ text:'Deletion cancelled', level: "info" });
                    return true;
                }
            });
        };
    }
    var mySpGrid = new Ext.grid.GridPanel({
        store: gridstore,
        id: gridType + "SpotlightGridId",
        columns: sptlght.utils.SpotlightUtils.gridColumns,
        stripeRows: true,
        autoExpandColumn: 'name',
        height: 350,
        width: 400,
        title: gridType,
        tbar:[
            {
                text:'Delete',
                icon: "images/star.png",
                cls:'x-btn-text-icon',
                tooltip:'Delete selected spotlights',
                handler : handlerFunction
            }
        ],
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : function(record, rowIndex, p, store) {
                if (this.showPreview) {
                    p.body = '<p>' + record.data.desc + '</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        }
    });
    mySpGrid.on("celldblclick", function (g, ri, ci, e) {
        var mySpGrid = Ext.getCmp(gridType + "SpotlightGridId");
        sptlght.utils.SpotlightUtils.dblclick(mySpGrid.getSelectionModel().getSelected().data.name);
    });

    mySpGrid.on("render", function () {
        if (gridstore.getTotalCount == 0) {
            if (gridType == 'System') {
                sptlght.utils.SpotlightUtils.getSystemSpotlightData(function() {
                    gridstore = new Ext.data.ArrayStore({
                        fields: sptlght.utils.SpotlightUtils.arrayFields,
                        data: sptlgtSystemArray
                    });

                });
            }
            if (gridType == 'Personal') {
                sptlght.utils.SpotlightUtils.getPersonalSpotlightData(function() {
                    gridstore = new Ext.data.ArrayStore({
                        fields: sptlght.utils.SpotlightUtils.arrayFields,
                        data: sptlgtPersonalArray
                    });

                });
            }
        }
    });

    return mySpGrid;
};

sptlght.utils.SpotlightUtils.loadSearchResultArray = function (myDataArray, jsonResult) {
    var jsonSearchArray = jsonResult.results;
    var sortedNameArray = [];
    var fileMap = [];
    for (var i = 0; i < jsonSearchArray.length; i++) {
        myDataArray[i] = translateSpotlightJson(jsonSearchArray[i]);
        sortedNameArray[i] = myDataArray[i][0];
        fileMap[myDataArray[i][0]] = myDataArray[i];

    }
    sortedNameArray.sort();
    //loop thru sortedNameArray
    var sortedJsonFilesObj = [];
    for (var si = 0; si < sortedNameArray.length; si++) {
        sortedJsonFilesObj[si] = fileMap[sortedNameArray[si]];
    }
    myDataArray = sortedJsonFilesObj;
    return myDataArray;
};

sptlght.utils.SpotlightUtils.loadPersonalResultArray = function (jsonResult, callback) {
    var myDataArray = [];
    var jsonSearchArray = jsonResult.results;
    var sortedNameArray = [];
    var fileMap = [];
    for (var i = 0; i < jsonSearchArray.length; i++) {
        myDataArray[i] = translateSpotlightJson(jsonSearchArray[i]);
        sortedNameArray[i] = myDataArray[i][0];
        fileMap[myDataArray[i][0]] = myDataArray[i];
    }
    sortedNameArray.sort();
    var sortedJsonFilesObj = [];
    for (var si = 0; si < sortedNameArray.length; si++) {
        sortedJsonFilesObj[si] = fileMap[sortedNameArray[si]];
    }
    sptlgtPersonalArray = sortedJsonFilesObj;
    callback();
};

sptlght.utils.SpotlightUtils.loadSystemResultArray = function (jsonResult, callback) {
    var myDataArray = [];
    var jsonSearchArray = jsonResult.results;
    var sortedNameArray = [];
    var fileMap = [];
    for (var i = 0; i < jsonSearchArray.length; i++) {
        myDataArray[i] = translateSpotlightJson(jsonSearchArray[i]);
        sortedNameArray[i] = myDataArray[i][0];
        fileMap[myDataArray[i][0]] = myDataArray[i];
    }
    sortedNameArray.sort();
    var sortedJsonFilesObj = [];
    for (var si = 0; si < sortedNameArray.length; si++) {
        sortedJsonFilesObj[si] = fileMap[sortedNameArray[si]];
    }
    sptlgtSystemArray = sortedJsonFilesObj;
    callback();
};


sptlght.utils.SpotlightUtils.arrayFields = [
    {
        name: 'name'
    },
    {
        name: 'alias'
    },
    {
        name: 'desc'
    }
];

sptlght.utils.SpotlightUtils.gridColumns = [
    {
        id       :'name',
        header   : 'Key',
        width    : 30,
        sortable : true,
        dataIndex: 'name'
    },
    {
        header   : 'Notes',
        width    : 125,
        sortable : true,
        dataIndex: 'alias'
    }
];

function translateSpotlightJson(jsonSearchArray) {
    var jsonObj = [];
    jsonObj[0] = jsonSearchArray.name;
    jsonObj[1] = jsonSearchArray.alias;
    jsonObj[2] = jsonSearchArray.desc;
    return jsonObj;
}

sptlght.utils.SpotlightUtils.selectedRecord = null;

sptlght.utils.SpotlightUtils.setSelectedRecord = function(rec) {
    sptlght.utils.SpotlightUtils.selectedRecord = rec;
};

sptlght.utils.SpotlightUtils.source = null;

sptlght.utils.SpotlightUtils.setSource = function(datasource) {
    sptlght.utils.SpotlightUtils.source = datasource;
};

sptlght.utils.SpotlightUtils.getSpotlightMenu = function(id) {
    return new Ext.menu.Menu({
        id: id,
        items: [
            {
                text: 'Spotlight',
                icon: "images/add-green.png",
                handler: sptlght.utils.SpotlightUtils.handleAddToSpotlight
            }
        ]
    });
};

sptlght.utils.SpotlightUtils.handleAddToSpotlight = function() {
    var spotlightWin = new Ext.Window({
        title: 'Spotlight',
        id: 'LIMSSpotlightId',
        width: 480,
        height: 200,
        autoScroll: true,
        //keys: [ getEnterClick('addSpotlightButtonId')],   
        keys: [
            {
                key: [Ext.EventObject.ENTER],
                fn: function() {
                    Ext.ComponentMgr.get('addSpotlightButtonId').fireEvent('click');
                }
            }
        ],
        modal: true,
        bodyStyle: 'padding:2px;',
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                border: false,
                items: [
                    {
                        xtype: 'combo',
                        id: sptlght.utils.SpotlightUtils.source + 'sptypeId',
                        fieldLabel: "Type",
                        value: 'Personal',
                        width: 100,
                        store: sptypeStore,
                        displayField: 'key',
                        valueField: 'value',
                        selectOnFocus: true,
                        mode: 'local',
                        typeAhead: true,
                        editable: false,
                        triggerAction: 'all',
                        margins: '0 5 0 0'
                    },
                    new Ext.form.TextField({
                        id: sptlght.utils.SpotlightUtils.source + "spdescId",
                        fieldLabel: "Notes",
                        width: 300,
                        allowBlank: true
                    })
                ]
            })
        ],
        buttons: [
            {
                text: 'Go',
                id: 'addSpotlightButtonId',
                handler: function() {
                    var postJson = new Object();
                    var desc = Ext.getCmp(sptlght.utils.SpotlightUtils.source + "spdescId").getValue();
                    var sptype = Ext.getCmp(sptlght.utils.SpotlightUtils.source + "sptypeId").getValue();
                    postJson["strainName"] = sptlght.utils.SpotlightUtils.selectedRecord[1];
                    postJson["alias"] = sptlght.utils.SpotlightUtils.selectedRecord[2];
                    if (sptlght.utils.SpotlightUtils.source == 'yseq' && sptlght.utils.SpotlightUtils.selectedRecord.length >= 15) {
                        postJson["alias"] = sptlght.utils.SpotlightUtils.selectedRecord[15];
                    }
                    if (sptlght.utils.SpotlightUtils.source == 'ycgs' && sptlght.utils.SpotlightUtils.selectedRecord.length >= 5) {
                        postJson["alias"] = sptlght.utils.SpotlightUtils.selectedRecord[4] + ":" + sptlght.utils.SpotlightUtils.selectedRecord[5];
                    }
                    postJson["desc"] = desc;
                    spotlightPanel.expand();
                    sptlght.utils.SpotlightUtils.postSpotlightData(sptype, sptlght.utils.SpotlightUtils.selectedRecord[1], postJson, function() {
                        spotlightWin.close();
                        if (sptype != "System") {
                            var pNewspot = perpstore.recordType; //Ext.getCmp("PersonalSpotlightGridId").getStore().recordType;
                            var psp = new pNewspot({
                                name: sptlght.utils.SpotlightUtils.selectedRecord[1],
                                alias: postJson['alias'],
                                desc: desc
                            });
                            spottabs.setActiveTab(0);
                            //Ext.getCmp("PersonalSpotlightGridId").getStore().add(psp);
                            perpstore.add(psp);
                        } else {
                            var Newspot = syspstore.recordType; //Ext.getCmp("SystemSpotlightGridId").getStore().recordType;
                            var sp = new Newspot({
                                name: sptlght.utils.SpotlightUtils.selectedRecord[1],
                                alias: postJson['alias'],
                                desc: desc
                            });
                            spottabs.setActiveTab(1);
                            syspstore.add(sp);
                        }
                    });
                }
            }
        ],
        layout: 'fit'
    });
    spotlightWin.show();
}
